<!-- @format -->

<template>
  <li
    class="comp-dropdown-item"
    :class="{
      'is-disabled': disabled,
      'is-divided': divided,
      'is-active': active,
    }"
    @click="handleClick"
  >
    <i v-if="icon" class="comp-dropdown-item__icon" :class="icon"></i>
    <span class="comp-dropdown-item__content">
      <slot></slot>
    </span>
  </li>
</template>

<script setup lang="ts">
import { inject } from 'vue'

  interface DropdownItemProps {
    command?: string | number | object
    disabled?: boolean
    divided?: boolean
    icon?: string
    active?: boolean
  }

  const props = withDefaults(defineProps<DropdownItemProps>(), {
    command: '',
    disabled: false,
    divided: false,
    icon: '',
    active: false,
  })

  const handleMenuItemClick = inject<
    (command: string | number | object, instance: any) => void
  >('handleMenuItemClick')

  const handleClick = (event: MouseEvent) => {
    if (props.disabled) {
      event.stopPropagation()
      return
    }

    // 阻止事件冒泡，避免触发外部点击事件
    event.stopPropagation()

    if (handleMenuItemClick) {
      handleMenuItemClick(props.command, {
        event,
        props,
      })
    }
  }
</script>

<style scoped>
  .comp-dropdown-item {
    list-style: none;
    line-height: 36px;
    padding: 0 20px;
    margin: 0;
    font-size: 14px;
    color: #606266;
    cursor: pointer;
    outline: none;
    transition:
      color 0.3s,
      background-color 0.3s;
    box-sizing: border-box;
    white-space: nowrap;
    display: flex;
    align-items: center;
  }

  .comp-dropdown-item:hover:not(.is-disabled) {
    background-color: #f5f7fa;
    color: #409eff;
  }

  .comp-dropdown-item.is-disabled {
    cursor: not-allowed;
    color: #c0c4cc;
    pointer-events: none;
    opacity: 0.7;
  }

  .comp-dropdown-item.is-divided {
    position: relative;
    margin-top: 6px;
    border-top: 1px solid #ebeef5;
  }

  .comp-dropdown-item.is-divided:before {
    content: '';
    height: 6px;
    display: block;
    margin: 0 -20px;
    background-color: #fff;
  }

  .comp-dropdown-item.is-active {
    color: #409eff;
    background-color: #ecf5ff;
    font-weight: 500;
  }

  .comp-dropdown-item__icon {
    margin-right: 8px;
    font-size: 16px;
    color: inherit;
  }

  .comp-dropdown-item__content {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  /* 在暗色主题下的样式 */
  :deep(.comp-dropdown--dark) .comp-dropdown-item {
    color: #e5eaf3;
  }

  :deep(.comp-dropdown--dark) .comp-dropdown-item:hover {
    background-color: #363637;
    color: #409eff;
  }

  :deep(.comp-dropdown--dark) .comp-dropdown-item.is-active {
    background-color: #18222c;
  }

  :deep(.comp-dropdown--dark) .comp-dropdown-item.is-divided::before {
    background-color: #4c4d4f;
  }
</style>
